#!/bin/bash

. /usr/lib/umm/umm_vars

Usage(){
    echo "Usage

    umm status                               - check MM status
    umm on [command to execute in mm mode]   - enforce MM mode.
    umm off [reboot]                         - continue boot or [reboot] into operational mode
    umm enable                               - enable MM functionality
    umm disable                              - disable MM functionality

"
}

if [  ! "z$UMM" == "zyes" ] ; then
    case $1 in

        "status" )
            echo "MM disabled"
            ;;
        "on" | "off" | "disable" )
            echo "MM already disabled"
            exit 1
            ;;
        "enable" )
            sed -i 's/UMM=.*/UMM=yes/' /etc/umm.conf
            ;;
        * )
            Usage
            ;;
    esac
else
    case $1 in
        "status" )
            if [ -f $UMM_FLAG ] ; then
                cat $UMM_FLAG
            else
                echo runlevel $(runlevel)
            fi
            ;;
        "on" )
            if [ ! -f $UMM_FLAG ] ; then
                shift
                [ -z "$*"  ] || echo "$*" > $UMM_DATA/UMM_CMD
                echo rebooting >>$UMM_FLAG
                mkdir -p $UMM_DATA/
                echo "1" >$UMM_DATA/UMM_ENFORCED
                reboot
            else
                echo MM already in state - $(cat $UMM_FLAG)
                exit 1
            fi
            ;;
        "off" )
            if [ -f $UMM_FLAG ] ; then
                if [ x$(cat $UMM_FLAG) == xrebooting ] ; then
                    echo MM now in state - $(cat $UMM_FLAG)
                else
                    rm $UMM_FLAG
                    if [ "x$2" == "xreboot" ] ; then
                        rm $UMM_DATA/UMM_DRC.var
                        sleep 1
                        reboot
                    fi
                fi
            else
                echo "MM already in off state"
                exit 1
            fi
            ;;
        "enable" )
                echo "MM already enabled"
                exit 1
            ;;
        "disable" )
            if [ -f $UMM_FLAG ] ; then
                echo "Current state is $(cat $UMM_FLAG) switch off first "
                exit 1
            else
                [ -f $UMM_DATA/UMM_ENFORCED ] && rm  $UMM_DATA/UMM_ENFORCED
                [ -f $UMM_DATA/UMM_CMD ] &&  rm  $UMM_DATA/UMM_CMD
                sed -i 's/UMM=.*/UMM=no/' /etc/umm.conf
            fi
            ;;
        * )
            Usage
            ;;
    esac
fi
